﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.ServiceModel.Dispatcher;
using Microsoft.Practices.ObjectBuilder2;
using Microsoft.Practices.Unity;
using System.ServiceModel;
using System.ServiceModel.Channels;

namespace WDA.Core
{
	/// <summary>
	/// <see cref="IInstanceProvider"/> implementation which uses Unity container to obtain instances
	/// classes implementing service contract.
	/// </summary>
	internal class ManagedInstanceProvider : IInstanceProvider
	{
		private readonly Type _contractType;
      private readonly string _serviceName;

		/// <summary>
		/// Servant container.
		/// </summary>
      [Dependency(WDAContainerNames.ServantContainerName)]
      public IUnityContainer ServantContainer { get; set; }

		/// <summary>
		/// Creates new <see cref="ManagedInstanceProvider"/> instance.
		/// </summary>
		/// <param name="contractType">CLR type of service contract.</param>
		/// <param name="serviceName">WDAB service name.</param>
		public ManagedInstanceProvider(Type contractType, string serviceName)
		{
			_contractType = contractType;
         _serviceName = serviceName;
		}

		#region IInstanceProvider Members
		public object GetInstance(InstanceContext instanceContext, Message message)
		{
         return ServantContainer.Resolve(_contractType, _serviceName);
		}
		public object GetInstance(InstanceContext instanceContext)
		{
			return GetInstance(instanceContext, null);
		}
		public void ReleaseInstance(InstanceContext instanceContext, object instance)
		{
         ServantContainer.Teardown(instance);
		}
		#endregion
	}
}
